package com.young.fragments.demo.lazy_show_demo.fms

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.young.fragments.databinding.ActivityLazyShowBinding
import com.young.lib_fragments.fms.BaseLazyFragment

/**
 * @author huangzehui
 * @date 12/3/2025 上午12:19 周三
 * @description 测试ViewPager2跳转的跟fragment
 */
class RootShowFragment : BaseLazyFragment(),OnClickListener {

    // binding
    private lateinit var mBinding:ActivityLazyShowBinding

    private val mFragmentStateAdapter by lazy {
        // 这里需要传入当前fragment，注意：必须是fragment已经添加了才可以，所以这里使用lazy来保证已经添加了
        // 否则出现  Fragment RootShowFragment{ad75301} (0a795b4e-67fe-49d1-9712-0986835e449d) has not been attached yet.
        object : FragmentStateAdapter(this) {

            override fun getItemCount(): Int {
                return 4
            }

            override fun createFragment(position: Int): Fragment {
                return when (position) {
                    0 -> {
                        LazyShowFragment1()
                    }

                    1 -> {
                        LazyShowFragment2()
                    }

                    2 -> {
                        LazyShowFragment3()
                    }

                    3 -> {
                        LazyShowFragment4()
                    }

                    else -> {
                        throw Exception("no fragment")
                    }
                }
            }

        }
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        mBinding = ActivityLazyShowBinding.inflate(inflater,container,false)
        return mBinding.root
    }

    override fun onFirstSupportVisible() {
        super.onFirstSupportVisible()
        initViewPager()
        initClick()
    }

    private fun initViewPager() {
        mBinding.vpContainer.offscreenPageLimit = 3
        mBinding.vpContainer.adapter = mFragmentStateAdapter
    }

    private fun initClick() {
        mBinding.btnPage1.setOnClickListener(this)
        mBinding.btnPage2.setOnClickListener(this)
        mBinding.btnPage3.setOnClickListener(this)
        mBinding.btnPage4.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v) {
            mBinding.btnPage1 -> {
                mBinding.vpContainer.currentItem = 0
            }

            mBinding.btnPage2 -> {
                mBinding.vpContainer.currentItem = 1
            }

            mBinding.btnPage3 -> {
                mBinding.vpContainer.currentItem = 2
            }

            mBinding.btnPage4 -> {
                mBinding.vpContainer.currentItem = 3
            }

            else -> {

            }
        }
    }

}